home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / hplip / base / pkit.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-10-28  |  14.0 KB  |  427 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import os.path as os
  6. import sys
  7. import re
  8. import time
  9. import cStringIO
  10. import ConfigParser
  11. import shutil
  12. import stat
  13. from base.logger import *
  14. from base.g import *
  15. from base.codes import *
  16. from base import utils, device
  17. import dbus
  18. import dbus.service as dbus
  19. import gobject
  20. import warnings
  21. warnings.simplefilter('ignore', DeprecationWarning)
  22.  
  23. class AccessDeniedException(dbus.DBusException):
  24.     _dbus_error_name = 'com.hp.hplip.AccessDeniedException'
  25.  
  26.  
  27. class UnsupportedException(dbus.DBusException):
  28.     _dbus_error_name = 'com.hp.hplip.UnsupportedException'
  29.  
  30.  
  31. class UsageError(dbus.DBusException):
  32.     _dbus_error_name = 'com.hp.hplip.UsageError'
  33.  
  34. POLICY_KIT_ACTION = 'com.hp.hplip'
  35. INSTALL_PLUGIN_ACTION = 'com.hp.hplip.installplugin'
  36.  
  37. def get_service_bus():
  38.     return dbus.SystemBus()
  39.  
  40.  
  41. def get_service(bus = None):
  42.     if not bus:
  43.         bus = get_service_bus()
  44.     
  45.     service = bus.get_object(BackendService.SERVICE_NAME, '/')
  46.     service = dbus.Interface(service, BackendService.INTERFACE_NAME)
  47.     return service
  48.  
  49.  
  50. class PolicyKitAuthentication(object):
  51.     
  52.     def __init__(self):
  53.         super(PolicyKitAuthentication, self).__init__()
  54.         self.pkit = None
  55.         self.auth = None
  56.  
  57.     
  58.     def is_authorized(self, action_id, pid = None):
  59.         if pid == None:
  60.             pid = os.getpid()
  61.         
  62.         pid = dbus.UInt32(pid)
  63.         authorized = self.policy_kit.IsProcessAuthorized(action_id, pid, False)
  64.         log.debug('is_authorized(%s) = %r' % (action_id, authorized))
  65.         return authorized == 'yes'
  66.  
  67.     
  68.     def obtain_authorization(self, action_id, widget = None):
  69.         if self.is_authorized(action_id):
  70.             return True
  71.         if not widget or widget.get_toplevel().window.xid:
  72.             pass
  73.         xid = 0
  74.         xid = dbus.UInt32(xid)
  75.         pid = dbus.UInt32(os.getpid())
  76.         granted = self.auth_agent.ObtainAuthorization(action_id, xid, pid)
  77.         log.debug('obtain_authorization(%s) = %r' % (action_id, granted))
  78.         return bool(granted)
  79.  
  80.     
  81.     def get_policy_kit(self):
  82.         if self.pkit:
  83.             return self.pkit
  84.         service = dbus.SystemBus().get_object('org.freedesktop.PolicyKit', '/')
  85.         self.pkit = dbus.Interface(service, 'org.freedesktop.PolicyKit')
  86.         return self.pkit
  87.  
  88.     policy_kit = property(get_policy_kit)
  89.     
  90.     def get_auth_agent(self):
  91.         if self.auth:
  92.             return self.auth
  93.         self.auth = dbus.SessionBus().get_object('org.freedesktop.PolicyKit.AuthenticationAgent', '/')
  94.         return self.auth
  95.  
  96.     auth_agent = property(get_auth_agent)
  97.  
  98.  
  99. class PolicyKitService(dbus.service.Object):
  100.     
  101.     def check_permission_v0(self, sender, action = POLICY_KIT_ACTION):
  102.         if not sender:
  103.             log.error('Session not authorized by PolicyKit')
  104.             raise AccessDeniedException('Session not authorized by PolicyKit')
  105.         sender
  106.         
  107.         try:
  108.             policy_auth = PolicyKitAuthentication()
  109.             bus = dbus.SystemBus()
  110.             dbus_object = bus.get_object('org.freedesktop.DBus', '/')
  111.             dbus_object = dbus.Interface(dbus_object, 'org.freedesktop.DBus')
  112.             pid = dbus.UInt32(dbus_object.GetConnectionUnixProcessID(sender))
  113.             granted = policy_auth.is_authorized(action, pid)
  114.             if not granted:
  115.                 log.error('Process not authorized by PolicyKit')
  116.                 raise AccessDeniedException('Process not authorized by PolicyKit')
  117.             granted
  118.             granted = policy_auth.policy_kit.IsSystemBusNameAuthorized(action, sender, False)
  119.             if granted != 'yes':
  120.                 log.error('Session not authorized by PolicyKit version 0')
  121.                 raise AccessDeniedException('Session not authorized by PolicyKit')
  122.             granted != 'yes'
  123.         except AccessDeniedException:
  124.             log.warning('AccessDeniedException')
  125.             raise 
  126.         except dbus.DBusException:
  127.             ex = None
  128.             log.warning('AccessDeniedException %r', ex)
  129.             raise AccessDeniedException(ex.message)
  130.  
  131.  
  132.     
  133.     def check_permission_v1(self, sender, connection, action = POLICY_KIT_ACTION):
  134.         if not sender or not connection:
  135.             log.error('Session not authorized by PolicyKit')
  136.             raise AccessDeniedException('Session not authorized by PolicyKit')
  137.         not connection
  138.         system_bus = dbus.SystemBus()
  139.         obj = system_bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority', 'org.freedesktop.PolicyKit1.Authority')
  140.         policy_kit = dbus.Interface(obj, 'org.freedesktop.PolicyKit1.Authority')
  141.         info = dbus.Interface(connection.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus/Bus', False), 'org.freedesktop.DBus')
  142.         pid = info.GetConnectionUnixProcessID(sender)
  143.         subject = ('unix-process', {
  144.             'pid': dbus.UInt32(pid, variant_level = 1) })
  145.         details = {
  146.             '': '' }
  147.         flags = dbus.UInt32(1)
  148.         cancel_id = ''
  149.         (ok, notused, details) = policy_kit.CheckAuthorization(subject, action, details, flags, cancel_id)
  150.         if not ok:
  151.             log.error('Session not authorized by PolicyKit version 1')
  152.         
  153.         return ok
  154.  
  155.  
  156.  
  157. class BackendService(PolicyKitService):
  158.     INTERFACE_NAME = 'com.hp.hplip'
  159.     SERVICE_NAME = 'com.hp.hplip'
  160.     LOGFILE_NAME = '/tmp/hp-pkservice.log'
  161.     
  162.     def __init__(self, connection = None, path = '/', logfile = LOGFILE_NAME):
  163.         if connection is None:
  164.             connection = get_service_bus()
  165.         
  166.         super(BackendService, self).__init__(connection, path)
  167.         self.name = dbus.service.BusName(self.SERVICE_NAME, connection)
  168.         self.loop = gobject.MainLoop()
  169.         self.version = 0
  170.         log.set_logfile('%s.%d' % (logfile, os.getpid()))
  171.         log.set_level('debug')
  172.  
  173.     
  174.     def run(self, version = None):
  175.         if version is None:
  176.             version = policykit_version()
  177.             if version is None:
  178.                 log.error('Unable to determine installed PolicyKit version')
  179.                 return None
  180.         
  181.         self.version = version
  182.         log.set_where(Logger.LOG_TO_CONSOLE_AND_FILE)
  183.         log.debug('Starting back-end service loop (version %d)' % version)
  184.         self.loop.run()
  185.  
  186.     
  187.     def installPlugin(self, src_dir, sender = None, connection = None):
  188.         if self.version == 0:
  189.             
  190.             try:
  191.                 self.check_permission_v0(sender, INSTALL_PLUGIN_ACTION)
  192.             except AccessDeniedException:
  193.                 e = None
  194.                 return False
  195.             
  196.  
  197.         None<EXCEPTION MATCH>AccessDeniedException
  198.         if self.version == 1:
  199.             if not self.check_permission_v1(sender, connection, INSTALL_PLUGIN_ACTION):
  200.                 return False
  201.         else:
  202.             log.error('installPlugin: invalid PolicyKit version %d' % self.version)
  203.             return False
  204.         self.check_permission_v1(sender, connection, INSTALL_PLUGIN_ACTION).debug("installPlugin: installing from '%s'" % src_dir)
  205.         if not copyPluginFiles(src_dir):
  206.             log.error('Plugin installation failed')
  207.             return False
  208.         return True
  209.  
  210.     installPlugin = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = 's', out_signature = 'b', sender_keyword = 'sender', connection_keyword = 'connection')(installPlugin)
  211.     
  212.     def shutdown(self, sender = None, connection = None):
  213.         log.debug('Stopping backend service')
  214.         self.loop.quit()
  215.         return True
  216.  
  217.     shutdown = dbus.service.method(dbus_interface = INTERFACE_NAME, in_signature = '', out_signature = 'b', sender_keyword = 'sender', connection_keyword = 'connection')(shutdown)
  218.  
  219.  
  220. class PolicyKit(object):
  221.     
  222.     def __init__(self, version = None):
  223.         if version is None:
  224.             version = policykit_version()
  225.             if version is None:
  226.                 log.error('Unable to determine installed PolicyKit version')
  227.                 return None
  228.         
  229.         self.bus = dbus.SystemBus()
  230.         self.obj = self.bus.get_object(POLICY_KIT_ACTION, '/')
  231.         self.iface = dbus.Interface(self.obj, dbus_interface = POLICY_KIT_ACTION)
  232.         self.version = version
  233.  
  234.     
  235.     def installPlugin(self, src_dir):
  236.         if self.version == 0:
  237.             auth = PolicyKitAuthentication()
  238.             if not auth.is_authorized(INSTALL_PLUGIN_ACTION):
  239.                 if not auth.obtain_authorization(INSTALL_PLUGIN_ACTION):
  240.                     return None
  241.             
  242.         
  243.         
  244.         try:
  245.             ok = self.iface.installPlugin(src_dir)
  246.             return ok
  247.         except dbus.DBusException:
  248.             e = None
  249.             log.debug('installPlugin: %s' % str(e))
  250.             return False
  251.  
  252.  
  253.     
  254.     def shutdown(self):
  255.         if self.version == 0:
  256.             auth = PolicyKitAuthentication()
  257.             if not auth.is_authorized(INSTALL_PLUGIN_ACTION):
  258.                 if not auth.obtain_authorization(INSTALL_PLUGIN_ACTION):
  259.                     return None
  260.             
  261.         
  262.         
  263.         try:
  264.             ok = self.iface.shutdown()
  265.             return ok
  266.         except dbus.DBusException:
  267.             e = None
  268.             log.debug('shutdown: %s' % str(e))
  269.             return False
  270.  
  271.  
  272.  
  273.  
  274. def copyPluginFiles(src_dir):
  275.     os.chdir(src_dir)
  276.     plugin_spec = ConfigBase('plugin.spec')
  277.     products = plugin_spec.keys('products')
  278.     BITNESS = utils.getBitness()
  279.     ENDIAN = utils.getEndian()
  280.     PPDDIR = sys_conf.get('dirs', 'ppd')
  281.     DRVDIR = sys_conf.get('dirs', 'drv')
  282.     HOMEDIR = sys_conf.get('dirs', 'home')
  283.     DOCDIR = sys_conf.get('dirs', 'doc')
  284.     CUPSBACKENDDIR = sys_conf.get('dirs', 'cupsbackend')
  285.     CUPSFILTERDIR = sys_conf.get('dirs', 'cupsfilter')
  286.     RULESDIR = '/etc/udev/rules.d'
  287.     processor = utils.getProcessor()
  288.     if processor == 'power_machintosh':
  289.         ARCH = 'ppc'
  290.     else:
  291.         ARCH = 'x86_%d' % BITNESS
  292.     if BITNESS == 64:
  293.         SANELIBDIR = '/usr/lib64/sane'
  294.         LIBDIR = '/usr/lib64'
  295.     else:
  296.         SANELIBDIR = '/usr/lib/sane'
  297.         LIBDIR = '/usr/lib'
  298.     copies = []
  299.     for PRODUCT in products:
  300.         MODEL = PRODUCT.replace('hp-', '').replace('hp_', '')
  301.         for s in plugin_spec.get('products', PRODUCT).split(','):
  302.             if not plugin_spec.has_section(s):
  303.                 log.error('Missing section [%s]' % s)
  304.                 return False
  305.             src = plugin_spec.get(s, 'src', '')
  306.             trg = plugin_spec.get(s, 'trg', '')
  307.             link = plugin_spec.get(s, 'link', '')
  308.             if not src:
  309.                 log.error("Missing 'src=' value in section [%s]" % s)
  310.                 return False
  311.             if not trg:
  312.                 log.error("Missing 'trg=' value in section [%s]" % s)
  313.                 return False
  314.             src = os.path.basename(utils.cat(src))
  315.             trg = utils.cat(trg)
  316.             copies.append((src, trg, link))
  317.         
  318.     
  319.     copies = utils.uniqueList(copies)
  320.     copies.sort()
  321.     os.umask(0)
  322.     for src, trg, link in copies:
  323.         if not os.path.exists(src):
  324.             log.debug('Source file %s does not exist. Skipping.' % src)
  325.             continue
  326.         
  327.         if os.path.exists(trg):
  328.             log.debug('Target file %s already exists. Replacing.' % trg)
  329.             os.remove(trg)
  330.         
  331.         trg_dir = os.path.dirname(trg)
  332.         if not os.path.exists(trg_dir):
  333.             log.debug('Target directory %s does not exist. Creating.' % trg_dir)
  334.             os.makedirs(trg_dir, 493)
  335.         
  336.         if not os.path.isdir(trg_dir):
  337.             log.error('Target directory %s exists but is not a directory. Skipping.' % trg_dir)
  338.             continue
  339.         
  340.         
  341.         try:
  342.             shutil.copyfile(src, trg)
  343.         except (IOError, OSError):
  344.             e = None
  345.             log.error('File copy failed: %s' % e.strerror)
  346.             continue
  347.             continue
  348.  
  349.         if not os.path.exists(trg):
  350.             log.error('Target file %s does not exist. File copy failed.' % trg)
  351.             continue
  352.         else:
  353.             os.chmod(trg, stat.S_IRWXU | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH)
  354.         if link:
  355.             if os.path.exists(link):
  356.                 log.debug('Symlink already exists. Replacing.')
  357.                 os.remove(link)
  358.             
  359.             log.debug('Creating symlink %s (link) to file %s (target)...' % (link, trg))
  360.             
  361.             try:
  362.                 os.symlink(trg, link)
  363.             except (OSError, IOError):
  364.                 e = None
  365.                 log.debug('Unable to create symlink: %s' % e.strerror)
  366.             except:
  367.                 None<EXCEPTION MATCH>(OSError, IOError)
  368.             
  369.  
  370.         None<EXCEPTION MATCH>(OSError, IOError)
  371.     
  372.     log.debug('Updating hplip.conf - installed = 1')
  373.     sys_state.set('plugin', 'installed', '1')
  374.     log.debug('Updating hplip.conf - eula = 1')
  375.     sys_state.set('plugin', 'eula', '1')
  376.     return True
  377.  
  378.  
  379. def run_plugin_command(required = True, plugin_reason = PLUGIN_REASON_NONE):
  380.     su_sudo = None
  381.     need_sudo = True
  382.     if utils.to_bool(sys_conf.get('configure', 'policy-kit')):
  383.         
  384.         try:
  385.             obj = PolicyKit()
  386.             su_sudo = '%s'
  387.             need_sudo = False
  388.             log.debug('Using PolicyKit for authentication')
  389.         except dbus.DBusException:
  390.             ex = None
  391.             log.error('PolicyKit NOT installed when configured for use')
  392.         except:
  393.             None<EXCEPTION MATCH>dbus.DBusException
  394.         
  395.  
  396.     None<EXCEPTION MATCH>dbus.DBusException
  397.     if os.geteuid() == 0:
  398.         su_sudo = '%s'
  399.         need_sudo = False
  400.     
  401.     if need_sudo:
  402.         su_sudo = utils.su_sudo()
  403.         if su_sudo is None:
  404.             log.error("Unable to find a suitable sudo command to run 'hp-plugin'")
  405.             return (False, False)
  406.     
  407.     req = '--required'
  408.     if not required:
  409.         req = '--optional'
  410.     
  411.     if utils.which('hp-plugin'):
  412.         cmd = su_sudo % 'hp-plugin -u %s --reason %s' % (req, plugin_reason)
  413.     else:
  414.         cmd = su_sudo % 'python ./plugin.py -u %s --reason %s' % (req, plugin_reason)
  415.     log.debug('%s' % cmd)
  416.     (status, output) = utils.run(cmd, log_output = True, password_func = None, timeout = 1)
  417.     return (status == 0, True)
  418.  
  419.  
  420. def policykit_version():
  421.     if os.path.isdir('/usr/share/polkit-1'):
  422.         return 1
  423.     if os.path.isdir('/usr/share/PolicyKit'):
  424.         return 0
  425.     return None
  426.  
  427.